package ljye.com.ljye.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import ljye.com.ljye.R;
import ljye.com.ljye.adapter.Introduce_IMG_adapter;
import ljye.com.ljye.adapter.Star_Teacher_GridViewAdapter;
import ljye.com.ljye.bean.Course_Details;
import ljye.com.ljye.bean.Home_Popular_Course;
import ljye.com.ljye.dialog.ConsultDialog;
import ljye.com.ljye.dialog.Sign_Dialog;
import ljye.com.ljye.utils.HttpUtils;
import ljye.com.ljye.utils.Utils;
import ljye.com.ljye.view.MyListView;
import ljye.com.ljye.view.ScrollView_Class;
import okhttp3.Request;
import okhttp3.Response;

import static ljye.com.ljye.App.client;


public class Activity_Course_Details extends Activity implements ScrollView_Class.OnScrollListener {
    private GridView gridView;
    private List<String> list;
    private ImageView back;
    private ImageView share;
    private ImageView top;
    private ScrollView_Class myScrollView;
    private int searchLayoutTop;
    private int mainheight;
    private int viewheight;
    private LinearLayout mainLayout;
    private RelativeLayout viewHead;
    private LinearLayout consult;//电话咨询
    private LinearLayout audition;//免费试听
    private LinearLayout appointment;//立即报名
    public View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.back://返回
                    finish();
                    break;
                case R.id.top://回顶
                    myScrollView.fullScroll(View.FOCUS_UP);
                    top.setVisibility(View.GONE);
                    break;
                case R.id.consult://电话咨询
                    final ConsultDialog dialog=new ConsultDialog(Activity_Course_Details.this);
                    dialog.setMessage("4000-999-027");
                    dialog.setYesOnclickListener("呼叫", new ConsultDialog.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4000999027"));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            dialog.dismiss();

                        }
                    });
                    dialog.setNoOnclickListener("取消", new ConsultDialog.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                    break;
                case R.id.appointment://立即报名
                    Sign_Dialog signUpDialog=new Sign_Dialog(Activity_Course_Details.this,details);
                    signUpDialog.show();
                    break;
                case R.id.audition://免费试听

                    break;
                case R.id.school_address://上课地址
                    startActivity(new Intent(Activity_Course_Details.this, Activity_map.class));
                    break;
                default:
                    break;
            }
        }
    };
    private Home_Popular_Course.DataBean courseDetails;
    private Gson gson;
    private ImageView classImg;
    private TextView className;
    private TextView price;
    private Course_Details details;
    private MyListView listviewImg;
    private TextView schoolName;
    private TextView schoolAddress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_details);

        initview();
        //获取上一个页面传递过来的课程信息
//        courseDetails = (Home_Popular_Course.DataBean) getIntent().getSerializableExtra("Course_Details");
//        if (null!=courseDetails) {
//            getdata();
//        }
        myScrollView.setOnScrollListener(this);
        back.setOnClickListener(listener);
        top.setOnClickListener(listener);
        consult.setOnClickListener(listener);
        audition.setOnClickListener(listener);
        appointment.setOnClickListener(listener);
        schoolAddress.setOnClickListener(listener);

        classImg.setImageResource(R.drawable.class_item);
        initIMG();//课程长图介绍
    }
    public void getdata() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder()
                            .url(HttpUtils.PATH + "/course/show/"+courseDetails.getCourse_id()+"?campus_id=1")
                            .build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        gson = new Gson();
                        details = gson.fromJson(string, Course_Details.class);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (null!= details){
                                    setdata();
                                }
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void setdata() {
        Course_Details.DataBean data = details.getData();
        //课程图片
        Picasso.with(Activity_Course_Details.this)
                .load(data.getImage_url())
//                .placeholder(R.drawable.ic_default_image)
                            .fit()//填充全部
                .into(classImg);
        //课程名称
        className.setText(data.getName());
        //课程价格
        price.setText(data.getMkt_price());

        //课程介绍 长图
        List<String> list = data.getMobile_body_app();
        Introduce_IMG_adapter adapter=new Introduce_IMG_adapter(Activity_Course_Details.this,list);
        listviewImg.setAdapter(adapter);
        setListViewHeight(listviewImg);
        //明星老师
        List<Course_Details.DataBean.TeachersBean> teachersList = data.getTeachers();
        setGridView(76,teachersList);//76指的是每个item的宽度 明星老师资料
        //上课地址
        String address = data.getCampus().getAddress();
        schoolAddress.setText(address);
        //所属机构
        String name = data.getCampus().getName();
        schoolName.setText(name);

    }
    private void initIMG(){
        List<String> imglist = new ArrayList<>();
        imglist.add("http://ww3.sinaimg.cn/large/610dc034jw1f5d36vpqyuj20zk0qo7fc.jpg");
        imglist.add("http://ww3.sinaimg.cn/large/610dc034jw1f5byokn81tj20dw0hiwfe.jpg");
        imglist.add("http://ww1.sinaimg.cn/large/7a8aed7bjw1f2sm0ns82hj20f00l8tb9.jpg");
        imglist.add("http://ww3.sinaimg.cn/large/7a8aed7bjw1f2x7vxkj0uj20d10mi42r.jpg");
        imglist.add("http://ww4.sinaimg.cn/large/7a8aed7bjw1eyaov0c9z4j20iz0sg40t.jpg");
        imglist.add("http://ww4.sinaimg.cn/large/7a8aed7bjw1exr0p4r0h3j20oy15445o.jpg");
        Introduce_IMG_adapter adapter=new Introduce_IMG_adapter(Activity_Course_Details.this,imglist);
        listviewImg.setAdapter(adapter);
        setListViewHeight(listviewImg);
    }

    private void initview() {
        gridView = (GridView) findViewById(R.id.grid);//横向明星老师
        back = (ImageView) findViewById(R.id.back);
        share = (ImageView) findViewById(R.id.share);
        top = (ImageView) findViewById(R.id.top);
        listviewImg = (MyListView)findViewById(R.id.listview_img);//课程介绍

        classImg = (ImageView) findViewById(R.id.class_img);//课程背景图片
        className = (TextView) findViewById(R.id.class_name);//课程名称
        price = (TextView) findViewById(R.id.price);//课程价格

        schoolName = (TextView) findViewById(R.id.school_name);//所属机构
        schoolAddress = (TextView) findViewById(R.id.school_address);//上课地址

        consult = (LinearLayout) findViewById(R.id.consult);//电话咨询
        audition = (LinearLayout) findViewById(R.id.audition);//免费试听
        appointment = (LinearLayout) findViewById(R.id.appointment);//立即报名
        mainLayout = (LinearLayout) findViewById(R.id.main_layout);
        viewHead = (RelativeLayout) findViewById(R.id.view_head);
        myScrollView = (ScrollView_Class)findViewById(R.id.myScrollView);
        ViewTreeObserver viewTreeObserver = mainLayout.getViewTreeObserver();

        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                mainheight = mainLayout.getHeight();
                mainLayout.getWidth();
            }
        });
        //head高度
        ViewTreeObserver viewvto = viewHead.getViewTreeObserver();
        viewvto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                viewHead.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                viewheight = viewHead.getHeight();
                viewHead.getWidth();
            }
        });
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
            searchLayoutTop = mainheight-viewheight;//获取searchLayout的顶部位置
        }
    }
    //明星老师
    private void setGridView(int width, List<Course_Details.DataBean.TeachersBean> list) {

        int size = list.size();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * width * density);
        int itemWidth = (int) (width * density);//item宽度
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        gridView.setLayoutParams(params); // 重点
        gridView.setColumnWidth(itemWidth); // 重点
        gridView.setHorizontalSpacing(0); // 间距
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setNumColumns(size); // 重点
        Star_Teacher_GridViewAdapter starTeacherAdapter = new Star_Teacher_GridViewAdapter(Activity_Course_Details.this, list);
        gridView.setAdapter(starTeacherAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView name = (TextView) view.findViewById(R.id.name);
                String s = name.getText().toString();

                Intent intent = new Intent(Activity_Course_Details.this, Activity_Teacher_Home.class);
                startActivity(intent);

                Utils.showToast(Activity_Course_Details.this, "name:" + s);
            }
        });
    }


    @Override
    public void onScroll(int scrollY) {
        Log.d("XXXXX", "scrollY:" + scrollY);
        if (scrollY>searchLayoutTop){
            top.setVisibility(View.VISIBLE);
        }else {
            top.setVisibility(View.GONE);
        }
    }
    //解决ScrollView包裹listview后只显示一个条目问题
    public void setListViewHeight(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
}
